﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager
{
    Transform ui_root_;
    Transform ui_root
    {
        get
        {
            if (ui_root_ == null)
            {
                ui_root_ = GameObject.Find("Canvas").transform;
            }
            return ui_root_;
        }
    }
    static UIManager instance_;
    public static UIManager instance
    {
        get
        {
            if (instance_ == null)
            {
                instance_ = new UIManager();
            }
            return instance_;
        }
    }

    public void Update()
    {
        List<Type> sLst = new List<Type>(uiPanleBaseCache.Keys);
        for (int i = 0; i < sLst.Count; i++)
        {
            uiPanleBaseCache[sLst[i]].Update();
        }
    }

    Dictionary<Type, UIPanelBase> uiPanleBaseCache = new Dictionary<Type, UIPanelBase>();
    Dictionary<Type, GameObject> uiObjCache = new Dictionary<Type, GameObject>();
    public static void ShowUI<T>(Action back = null) where T: UIPanelBase,new ()
    {
        CloseUI<T>();
        //T t = (T)Activator.CreateInstance(typeof(T));
        T t = new T();
        instance.uiPanleBaseCache[typeof(T)] = t;
        GameObject uiPrefab = Resources.Load<GameObject>("ui_prefab/" + typeof(T));
        if (uiPrefab != null)
        {
            Transform uiRoot = GameObject.Instantiate<GameObject>(uiPrefab).transform;
            uiRoot.name = uiPrefab.name;
            t.OnInit(uiRoot);
            instance.uiObjCache[typeof(T)] = uiRoot.gameObject;
            uiRoot.SetParent(instance.ui_root, false);
            uiRoot.SetAsLastSibling();
            if (back != null)
            {
                back();
            }
        }
    }

    public static T GetUIPanelByType<T>()where T: UIPanelBase, new()
    {
        
        if (instance.uiPanleBaseCache.ContainsKey(typeof(T)))
        {
            return (T)instance.uiPanleBaseCache[typeof(T)];
        }
        return null;
    }

    public static void CloseUI<T>() where T : UIPanelBase
    {
        if (instance.uiPanleBaseCache.ContainsKey(typeof(T)))
        {
            instance.uiPanleBaseCache[typeof(T)].OnClose();
            instance.uiPanleBaseCache.Remove(typeof(T));
            if (instance.uiObjCache[typeof(T)])
            {
                GameObject.Destroy(instance.uiObjCache[typeof(T)]);
            }
            instance.uiObjCache.Remove(typeof(T));
        }
    }
}

public interface UIBase
{
    void OnInit(Transform root);
    void Update();
    void OnClose();
}
public class UIPanelBase : UIBase
{
    public UIPanelBase() { }
    public virtual void OnInit(Transform root){}
    public virtual void OnClose(){}
    public virtual void Update(){}
}